package com.imooc.ad.advice;
/*
 * @author Qihs
 */

import com.imooc.ad.annotation.IgnoreResponseAdvice;
import com.imooc.ad.vo.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

//统一拦截,不知道拦截类型，所以使用泛型
@RestControllerAdvice
public class CommonResponseAdvice implements ResponseBodyAdvice<Object> {

    //判断拦截的条件
    @Override
    public boolean supports(MethodParameter methodParameter,
                            Class<? extends HttpMessageConverter<?>> aClass) {
        //@IgnoreResponseAdvice,自己创建的注释
        //如果类被@IgnoreResponseAdvice注释，不进行拦截判断
        //getDeclaringClass获取类的声明
        if (methodParameter.getDeclaringClass().isAnnotationPresent(
                IgnoreResponseAdvice.class
        )){
            return false;
        }
        //如果类被@IgnoreResponseAdvice注释，不进行拦截判断
        if (methodParameter.getMethod().isAnnotationPresent(
                IgnoreResponseAdvice.class
        )){
            return false;
        }
        return false;
    }
    //在写入响应之前，拦截符合条件的类或者方法，并进行操作
    @Override
    @Nullable
    @SuppressWarnings("all") //屏蔽私有警告信息
    public Object beforeBodyWrite(@Nullable Object o,
                                  MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        //
        CommonResponse<Object> response = new CommonResponse<>(0, "");
        //如果返回对象是 o 是空，直接返回，代表没有data
        if (null == o){
            return response;
        }
        //如果返回对象是 o 是CommonResponse,不需要进行处理
        else if (o instanceof  CommonResponse){
            response =  (CommonResponse<Object>) o;
        }
        //如果返回对象是 o 是普通的返回对象,需要包装处理
        else {
            response.setData(o);
        }

        return response;
    }
}
